package com.netty.io.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GroupchatClient {

    private final String HOST = "127.0.0.1";

    private final int PORT = 8089;

    private Selector selector;

    private SocketChannel socketChannel;

    private InetSocketAddress socketAddress;

    public GroupchatClient() throws Exception {
        selector = Selector.open();
        socketAddress = new InetSocketAddress(HOST, PORT);
        socketChannel = SocketChannel.open(socketAddress);
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
    }

    public void sendData(String message) throws IOException {

        ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes());
        socketChannel.write(byteBuffer);
    }

    public void readData() throws IOException {

        int select = selector.select();
        if (select > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    SocketAddress clientName = null;
                    try {
                        int read = socketChannel.read(byteBuffer);
                        clientName = socketChannel.getRemoteAddress();
                        String message = new String(byteBuffer.array(), 0, read);
                        System.out.println(clientName + "发送数据" + message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                iterator.remove();
            }
        }
    }

    public static void main(String[] args) throws Exception {


        ExecutorService executorService = Executors.newFixedThreadPool(5);
        GroupchatClient groupchatClient = new GroupchatClient();

        Runnable runnable = () -> {
            while (true) {
                try {
                    groupchatClient.readData();
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();


        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String nextLine = scanner.nextLine();
            groupchatClient.sendData(nextLine);
        }
        ;
    }
}
